<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/4/3
 * Time: 15:55
 */

namespace app\middleware;

use think\facade\Cache;
use think\Response;
use think\Request;
use \Closure;
/**校验请求
 * Class Auth
 * @package app\middleware
 */
class ApiAuth
{
    private $filter = [
        'login',
        'register',
        'logout',
        'test'
    ]; // 跳过校验

    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
//        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Methods:POST,GET'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin,Authorization'); // 设置允许自定义请求头的字段
//        // 校验请求方式
        if (!$request->isPost()) return jsonFail('不允许的请求方式');
//        if (!in_array($request->action(true), $this->filter)) {
//            // 校验参数签名
//            if (checkSign($request->param()) == false) return jsonFail('参数验签失败');
//            // 校验token
//            $token = $request->header('authorization');
//            if ($token == null) return jsonFail('登录态失效，请重新登录');
//            $info = Cache::store('redis')->handler()->get($token);
//            if (!$info) return jsonFail('登录态失败,请重新登录');
//            $request->info = $info;
//        }
         event('ApiVisit',[2,'张三']);
        return $next($request);
    }

    /**进行额外操作
     * @param Response $response
     */
    public function end(Response $response)
    {
        // 回调行为
//        var_dump($response->getData());
    }
}